<?php
	require_once("../data/common.php");

	set_time_limit(600); //10 minutes time limit should be enough at this point.
	
	$sql = "SELECT * FROM variables WHERE name = 'database_revision'";
	$stmt = $dbh->prepare($sql);
	if ($stmt->execute() === FALSE) {
		die("Unfortunately you're using old database layout and you need to first upgrade that manually before running me.");
	}
	$row = $stmt->fetch();
	$stmt = null;
	if ($row === FALSE) {
		die("Something went wrong when searching the database version from the database.");
	}
	$db_rev = $row["value"];
	echo '<pre>'; //Make sure this looks the same whether run from command line or web browser.
	echo "You currently have database version ".$db_rev."\n";

	$changes = array();
	////////////////////////////////////////////////////////////////////////
	// Developers! Add new commands to be run in the bottom of this list! //
	////////////////////////////////////////////////////////////////////////
	
	// Leave the old commands as is for old users to upgrade as well.
	
	// Every command increases the revision of the database by one and only
	// one command can be run at a time (No command separation with ";")
	
	// $changes[<current revision for database +1>][0] = '<Command to be run>'; $changes[<current revision for database +1>][1] = "<Short description>";
	// There's couple of examples in the next comment.

	/*
	$changes[1][0] = 'SELECT * FROM variables'; $changes[1][1] = "Test revision change";
	$changes[2][0] = 'SELECT * FROM users'; $changes[2][1] = "Test revision change 2";
	*/
	
	
	
	$db_rev_ready = $db_rev;
	foreach($changes as $key => $command) {
		if ($key > $db_rev) {
			echo "Applying the following update: $key $command[1] \n";
			$sql = $command[0];
			$stmt = $dbh->prepare($sql);
			if ($stmt->execute() === FALSE) {
				$error = var_export($stmt->errorInfo(), true);
				die("\nSOMETHING WENT WRONG! Please seek help from the developers.\nGive them this information:\n\nDatabase upgrade failed: $command[1] $command[0]\nPDO returned this information:\n$error ");
			}
			$row = $stmt->fetch();
			$stmt = null;
			if ($key > $db_rev_ready) {
				$db_rev_ready = $key;
			}
		}
	}
	
	if ($db_rev_ready != $db_rev) {
		echo "Updated database from version $db_rev to $db_rev_ready \n\nUpdating the version in database... ";
		$sql = 'UPDATE variables SET value = "'.$db_rev_ready.'" WHERE name = "database_revision"';
		$stmt = $dbh->prepare($sql);
		if ($stmt->execute() === FALSE) {
			die("\nSomething went wront when updating the database version, it should most likely be $db_rev_ready.");
		} else {
			echo "Successful.\n";
		}
		$row = $stmt->fetch();
		$stmt = null;
	} else {
		echo "No changes for the database are required.\n";
	}
	echo "Script done.\n";
	echo '</pre>';
?>